"use client";

import { usePathname, useRouter } from "next/navigation";
import { useEffect } from "react";
import { useSession } from "next-auth/react";

interface RequireRoleProps {
  children: React.ReactNode;
  allowedRoles: string[];
}

export function RequireRole({ children, allowedRoles }: RequireRoleProps) {
  const { data: session, status } = useSession();
  const router = useRouter();
  const pathname = usePathname(); // ✅ 获取当前路径

  useEffect(() => {
    if (status === "unauthenticated") {
      router.push("/login");
    } else if (status === "authenticated") {
      const role = session?.user?.role;
      const username = session?.user?.name;

      // 1. 角色不在允许范围
      if (!allowedRoles.includes(role)) {
        router.push("/login");
        return;
      }

      // 2. 如果是 student，额外校验路径最后段和用户名是否一致
      if (role === "student") {
        const pathSegments = pathname.split("/");
        const lastSegment = pathSegments[pathSegments.length - 1];

        if (lastSegment !== username) {
          router.push("/login"); // ❌ 跳转无权限页
          return;
        }
      }
    }
  }, [status, session, allowedRoles, router, pathname]);

  if (status === "loading" || !session) return null;

  // 验证通过
  if (allowedRoles.includes(session.user.role)) {
    return <>{children}</>;
  }

  return null;
}
